<?php
/*
 * uclient的hooks
 * 
 * $Id$
 */

//安装uclient时，创建相关的缓存目录
function __on_install_uclient($rst) {
	if (! is_dir ( APPDATA_PATH . 'uclient/cache' )) {
		return @mkdir ( APPDATA_PATH . 'uclient/cache', 0775, true );
	}
	return true;
}
bind ( 'install_plugin_cn.usephp.uclient', '__on_install_uclient' );

function __the_uclient_option($group){
	$group['uclient'] = '<i class="icon-user"></i>UCenter配置';
	return $group;
}
bind('get_core_option_group', '__the_uclient_option');
//检查用户名在ucenter中是否存在 
function _uclient_check_uname($rst, $value, $data) {
	init_uclient_config ();
	$rst = uc_user_checkname ( $value );
	switch ($rst) {
		case '1' :
			$rst = true;
			break;
		case '-1' :
			$rst = '用户名不合法';
			break;
		case '-2' :
			$rst = '包含不允许注册的词语';
			break;
		case '-3' :
			$rst = '用户名已经存在';
			break;
		default :
			$rst = 'Ucenter返回了未知错误';
	}
	return $rst;
}
bind ( 'check_vip_account', '_uclient_check_uname', 10, 3 );
//检查EMAIL在ucenter中是否存在 
function _uclient_check_vip_email($rst, $value, $data) {
	init_uclient_config ();
	$rst = uc_user_checkemail ( $value );
	switch ($rst) {
		case '1' :
			$rst = true;
			break;
		case '-4' :
			$rst = 'Email 格式有误';
			break;
		case '-5' :
			$rst = 'Email 不允许注册';
			break;
		case '-6' :
			$rst = '该 Email 已经被注册';
			break;
		default :
			$rst = 'Ucenter返回了未知错误';
	}
	return $rst;
}
bind ( 'check_vip_email', '_uclient_check_vip_email', 10, 3 );
//在本系统新增了会员之后，同步到ucenter
function __syncuser2ucenter($user) {
	init_uclient_config ();
	if (! $user ['password']) {
		$user ['password'] = rand ( 10000000, 99999999 );
	}
	if (isset ( $user ['reg_ip'] )) { //新增
		uc_user_register ( $user ['account'], $user ['password'], $user ['email'], '', '', $user ['reg_ip'] );
	} else if ($user ['account'] == $user ['old_account']) { //不改名
		uc_user_edit ( $user ['account'], '', $user ['password'], $user ['email'], 1 );
	} else if ($user ['account'] != $user ['old_account']) { //改了名，就是删除原有的用户
		$ucu = uc_get_user ( $user ['old_account'] );
		if ($ucu) {
			uc_user_delete ( $ucu [0] );
		}
		uc_user_register ( $user ['account'], $user ['password'], $user ['email'], '', '', $user ['reg_ip'] );
	}
	return $user;
}
bind ( 'on_save_vip_user', '__syncuser2ucenter' );
//检查同步登录
function __uclient_synlogin_check() {
	$auth = cookie ( 'vip_auth', '' );
	$logined = cookie ( 'vip_authed', 0 );
	if ($auth && ! $logined) {
		$auth = ntzauthcode ( $auth, 'DECODE' );
		if ($auth) {
			$auths = explode ( "\t", $auth );
			if (count ( $auths ) == 2) {
				$vipM = new VipUserModel ();
				if ($vipM->login ( $auths [0], $auths [1] )) {
					scookie ( 'vip_authed', 1 );
				}
			}
		}
	}
}
bind ( 'kernel_started', '__uclient_synlogin_check' );